package com.zego.wawaji.ui.play;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentActivity;

import com.noble.library.basic.Constant;
import com.noble.library.basic.sp.PSP;
import com.noble.library.observer.MsgMgr;
import com.noble.medialib.notify.MediaNotifyUtils;
import com.zego.wawaji.R;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.ui.bean.user.UserDetail;
import com.zego.wawaji.ui.bean.wawa.WawaJi;
import com.zego.wawaji.ui.dialog.CatchWawaDialog;
import com.zego.wawaji.ui.dialog.PickerDialogUtil;
import com.zego.wawaji.ui.play.dialog.PlayAwardDialog;
import com.zego.wawaji.wawaji_client.AppTinkerLike;
import com.zego.wawaji.wawaji_client.cmd.CommandUtil;
import com.zego.wawaji.wawaji_client.play.BoardState;
import com.zego.wawaji.wawaji_client.play.PlayStatus;
import com.zego.wawaji.wawaji_client.util.PreferenceUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 游戏帮助类
 */
public class PlayHelper {
    public static int rspSeq;
    public static int mSwitchCameraTimes = 0;     // 切换摄像头次数, 重定义方向键
    public static void setSwitchTimes(int times) {
        mSwitchCameraTimes = times;
    }

    private static CountDownTimer mCountDownTimerReplay; // 重玩倒计时

    /**
     * 处理游戏结果
     */
    public static void handleGameResult(final int rspSeq, Map<String, Object> data) {
        if (data == null) {
            CommandUtil.getInstance().printLog("[handleGameResult], data is null");
            return;
        }
        final int result = ((Double) data.get("result")).intValue();  // 游戏结果

        final Map<String, Object> player = (Map<String, Object>) data.get("player");
        if (player == null) {
            CommandUtil.getInstance().printLog("[handleGameResult], player is null");
            return;
        }

        // 不是自己的通知，如果是成功记录,通知房间内用户抓中记录, 否则抛掉
        if (!PreferenceUtil.getInstance().getUserID().equals(player.get("id"))) {
            CommandUtil.getInstance().printLog("[handleGameResult], not my message, don't care");
            if (result == 1) {
                handleSucResult(player);
            }
            return;
        }

//        // 发送确认游戏结果CMD, 雪豹，苏瑞娃娃机使用
//        if (PlayStatus.getCurrentBoardSate() != BoardState.WaitingGameResult) {
//            String sessionData = (String) data.get("session_data");
//            CommandUtil.getInstance().confirmGameResult(rspSeq, sessionData);
//            return;
//        }

        PlayStatus.setCurrentBoardSate(BoardState.WaitingReplay);
        handleResult(result, rspSeq, player);
    }

    /**
     * Server板拿不到的话，通过老孙拿结果
     */
    public static void handleResult(int result, int rspSeq, Map<String, Object> player) {
        UserDetail userDetail = ModuleMgr.getCenterMgr().getMyInfo();
        if (userDetail.getWwNum() == 0 && userDetail.getCatchNum() == 0 && result != 1) {  // 首次玩并且失败
            ModuleMgr.getWawaMgr().reqGameFirst(response -> {
                MsgMgr.getInstance().sendMsg(MsgType.MT_Update_MyInfo, null);
                if (!response.isOk()) {
                    handleResult(result, player, rspSeq, "");
                    return;
                }

                JSONObject jsonObject = response.getResponseObject();
                String failAwardTitle = jsonObject.optString("Title");
                String failAwardContent = jsonObject.optString("Content");
                handleFirstFail(rspSeq, "", failAwardTitle, failAwardContent);
            });
        } else {
            handleResult(result, player, rspSeq, "");
        }
    }

    /**
     * 首抓未中处理
     */
    private static void handleFirstFail(final int rspSeq, final String sessionData, String failAwardTitle, String failAwardContent) {
        ModuleMgr.getWawaMgr().reqGameOver(-1, null); // 首抓失败

        final PlayAwardDialog dialog = new PlayAwardDialog((FragmentActivity) AppTinkerLike.getActivity(), failAwardTitle, failAwardContent);
        dialog.show();

        final WawaJi wawaJi = ModuleMgr.getWawaMgr().getLastWawaJi();
        dialog.setPositiveButton(v -> {
            dialog.dismiss();
            mCountDownTimerReplay.cancel();
            ModuleMgr.getWawaMgr().reqGameApply(wawaJi.getId(), wawaJi.getWwTypeId(), response -> {
                if (!response.isOk()) {
                    resetPlayBtn(rspSeq, sessionData);
                    return;
                }
                // 确认上机
                CommandUtil.getInstance().confirmBoard(rspSeq, sessionData, 1, () -> PToast.showShort("连接服务器失败了, 请重新开始预约!"));
            });
        });
        // 放弃上机
        dialog.setNegativeButton(v -> {
            mCountDownTimerReplay.cancel();
            resetPlayBtn(rspSeq, sessionData);
            dialog.dismiss();
        });

        mCountDownTimerReplay = new CountDownTimer(5000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
                    dialog.setCountTimes(AppTinkerLike.getActivity().getString(R.string.game_fail_replay, ((millisUntilFinished / 1000) + 1) + ""));
                }
            }

            @Override
            public void onFinish() {
                if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
                    resetPlayBtn(rspSeq, sessionData);
                    dialog.dismiss();
                }
            }
        }.start();
    }

    /**
     * 处理结果
     */
    private static void handleResult(int result, Map<String, Object> player, final int rspSeq, final String sessionData) {
        ModuleMgr.getWawaMgr().reqGameOver(result != 1 ? -1 : 1, null);

        final CatchWawaDialog catchWawaDialog = new CatchWawaDialog((FragmentActivity) AppTinkerLike.getActivity());
        catchWawaDialog.setCancelableOutTouch(false);
        catchWawaDialog.show();
        if (result != 1) {  // 未抓中
            catchWawaDialog.setTitle("好遗憾，没有抓中哎！");
            catchWawaDialog.setImgCenter(R.drawable.no_data);
        } else {
            playGameResultSound();
            handleSucResult(player);
        }

        final WawaJi wawaJi = ModuleMgr.getWawaMgr().getLastWawaJi();
        catchWawaDialog.setPositiveButton(v -> {
            catchWawaDialog.dismiss();
            mCountDownTimerReplay.cancel();
            ModuleMgr.getWawaMgr().reqGameApply(wawaJi.getId(), wawaJi.getWwTypeId(), response -> {
                if (!response.isOk()) {
                    resetPlayBtn(rspSeq, sessionData);
                    return;
                }
                // 确认上机
                CommandUtil.getInstance().confirmBoard(rspSeq, sessionData, 1, () -> PToast.showShort("连接服务器失败了, 请重新开始预约!"));
            });
        });
        // 放弃上机
        catchWawaDialog.setNegativeButton(v -> {
            mCountDownTimerReplay.cancel();
            resetPlayBtn(rspSeq, sessionData);
            catchWawaDialog.dismiss();
        });

        mCountDownTimerReplay = new CountDownTimer(5000, 500) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
                    catchWawaDialog.setCountTimes(AppTinkerLike.getActivity().getString(R.string.game_replay, ((millisUntilFinished / 1000) + 1) + ""));
                }
            }

            @Override
            public void onFinish() {
                if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
                    resetPlayBtn(rspSeq, sessionData);
                    catchWawaDialog.dismiss();
                }
            }
        }.start();
    }

    private static void resetPlayBtn(int rspSeq, String sessionData) {
        CommandUtil.getInstance().confirmBoard(rspSeq, sessionData, 0, null);
        MsgMgr.getInstance().delay(() -> MsgMgr.getInstance().sendMsg(MsgType.MT_Re_Init_Game, null), 500);
    }

    /**
     * 处理游戏抓中结果
     */
    private static void handleSucResult(Map<String, Object> player) {
        MsgMgr.getInstance().sendMsg(MsgType.MT_Game_Suc, player);
    }

    /**
     * 是否准备游戏弹框
     */
    public static void handleGameReady(FragmentActivity activity, final int rspSeq, Map<String, Object> data) {
        if (data == null) {
            return;
        }

        // 处于等待重玩游戏
        if (PlayStatus.getCurrentBoardSate() == BoardState.WaitingReplay) {
            return;
        }

        Map<String, Object> player = (Map<String, Object>) data.get("player");
        if (player == null) return;

        // 不是自己的消息
        if (!PreferenceUtil.getInstance().getUserID().equals(player.get("id"))) {
            return;
        }

        if (PlayStatus.getCurrentBoardSate() == BoardState.Applying) {
            PlayStatus.setCurrentBoardSate(BoardState.WaitingBoard);
        }

        if (PlayStatus.getCurrentBoardSate() != BoardState.WaitingBoard) {
            return;
        }
        final String sessionData = (String) data.get("session_data");
        PickerDialogUtil.showStartGameDialog(activity, rspSeq, sessionData);
    }

    public static void reset() {
        releasePlay();
        MediaNotifyUtils.stopSound();
        mSwitchCameraTimes = 0;
        if (mCountDownTimerReplay != null) {
            mCountDownTimerReplay.cancel();
        }
    }

    // ================================== 音乐管理 =====================
    private static List<MediaPlayer> mediaPlayerList = new ArrayList<>();  // 维护播放对象

    /**
     * 注册
     */
    public static void attachPlayer(MediaPlayer mMediaPlayer) {
        if (mediaPlayerList == null)
            mediaPlayerList = new ArrayList<>();
        mediaPlayerList.add(mMediaPlayer);
    }

    private static MediaPlayer bgmMedia;
    private static AssetFileDescriptor afd;

    /**
     * 背景音乐
     */
    public static void playSound() {
        boolean isPlay = PSP.getInstance().getBoolean(Constant.SET_BGM, true);
        if (!isPlay) return;

        try {
            if (afd == null) {
                AssetManager assetManager = AppTinkerLike.getContext().getAssets();
                afd = assetManager.openFd("ring01.mp3");
            }
            bgmMedia = new MediaPlayer();
            attachPlayer(bgmMedia);
            bgmMedia.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            bgmMedia.setLooping(false);
            bgmMedia.prepare();
            bgmMedia.start();
            bgmMedia.setVolume(0.5f, 0.5f);

            bgmMedia.setOnCompletionListener(mp -> bgmMedia.start());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void stopPlay() {
        if (mediaPlayerList == null) return;
        for (MediaPlayer mediaPlayer : mediaPlayerList) {
            mediaPlayer.stop();
        }
    }

    public static void releasePlay() {
        if (mediaPlayerList == null) return;
        for (MediaPlayer mediaPlayer : mediaPlayerList) {
            mediaPlayer.release();
        }
        mediaPlayerList.clear();
    }

    private static AssetFileDescriptor btnAfd;

    /**
     * 按钮点击音效
     */
    public static void playBtnSound() {
        boolean isPlay = PSP.getInstance().getBoolean(Constant.SET_VOICE, true);
        if (!isPlay) return;

        try {
            if (btnAfd == null) {
                AssetManager assetManager = AppTinkerLike.getContext().getAssets();
                btnAfd = assetManager.openFd("btn.wav");
            }
            MediaNotifyUtils.playSound(btnAfd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static AssetFileDescriptor gameAfd;

    /**
     * 抓中游戏音效
     */
    public static void playGameResultSound() {
        boolean isPlay = PSP.getInstance().getBoolean(Constant.SET_BGM, true);
        if (!isPlay) return;


        try {
            if (gameAfd == null) {
                AssetManager assetManager = AppTinkerLike.getContext().getAssets();
                gameAfd = assetManager.openFd("catch.mp3");
            }
            MediaNotifyUtils.playSound(gameAfd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
